package com.yunwushanhe.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunwushanhe.student.bean.JwtManager;
import com.yunwushanhe.student.bean.ManagerToken;
import com.yunwushanhe.student.bean.req.ManagerLoginReq;
import com.yunwushanhe.student.bean.ret.Result;
import com.yunwushanhe.student.entity.Manager;
import com.yunwushanhe.student.mapper.ManagerMapper;
import com.yunwushanhe.student.service.ManagerService;
import com.yunwushanhe.student.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class ManagerServiceImpl implements ManagerService {

    @Resource
    private ManagerMapper managerMapper;

    @Override
    public Result<ManagerToken> login(ManagerLoginReq loginReq) {
        LambdaQueryWrapper<Manager> qw = new LambdaQueryWrapper<>();
        qw.eq(Manager::getUserName,loginReq.getUserName())
            .eq(Manager::getPwd,loginReq.getPwd());
        Manager managerUser = managerMapper.selectOne(qw);
        if(managerUser == null){
            return Result.fail("用户名或者密码错误！");
            // 这里可以思考一下，因为Java是泛型机制，这里返回的泛型标识符与方法要求的是否一致
        }
        ManagerToken managerToken = generateToken(managerUser);
        return Result.ok(managerToken);
    }

    private ManagerToken generateToken(Manager managerUser) {
        JwtManager jwtManager = new JwtManager();
        BeanUtils.copyProperties(managerUser,jwtManager);

        String token = JwtUtil.getToken(jwtManager);

        ManagerToken managerToken = new ManagerToken();
        BeanUtils.copyProperties(jwtManager,managerToken);

        managerToken.setToken(token);
        return managerToken;
    }
}
